package com.dx.ss.example.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

@RestController
public class TestController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/k8s", method = {RequestMethod.GET})
    public String insert() {
        List<ServiceInstance> list = discoveryClient.getInstances("order");

        ServiceInstance serviceInstance = list.get(0);
        URI uri = serviceInstance.getUri();
        System.out.println(uri);
        testUri(uri.toString());
        return list.toString();
    }

    public void testUri(String uri) {
        URL url = null;
        try {
            url = new URL(uri);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            System.out.println("连接可用");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}